<?php
App::import('common.Core.CRequest');
App::import('common.View.View');
class BaseController{

	/**
	 * Set by Dispatcher
	 * @var action
	 */
	public $request;
	
	public $response;
	
	public $view;
	/**
	 * Set by Dispatcher
	 * @var action
	 */
	public $action; 
	
	
	public $enableAuthorize = false;
	
	public $allow = array();
	
	private $isAuthorized = false;
	
	protected $use_models = array();
	
	protected $models;
	
	public function BaseController(){
		$this->view = new View();
		$this->response = new CResponse();
		$this->_loadModelsOnInit();
	}

	public function execute(){
		
		$this->beforeAction();
		$this->exeAction();
		$this->afterAction();
		
	}
	
	public function beforeAction(){
		
	}
	
	public function afterAction(){
		
	}

	public function authorize(){
		return true;
	}

	private function exeAction(){
		if($this->enableAuthorize == true){
			if(!in_array($this->action, $this->allow) && $this->authorize() == true){
				$this->isAuthorized = true;
			}
			
			if($this->isAuthorized == true || in_array($this->action, $this->allow)){
				$this->_exeAction();
			}
			else
				echo 'Sorry, authorize failed';
		}
		else{
			$this->_exeAction();
		}
		
	}
	
	private function _exeAction(){
		$action = $this->action;
		$this->$action();
	}
	
	private function _loadModelsOnInit(){
		foreach ($this->use_models as $model){
			App::import('app.Model.'.$model);
			$this->models[$model] = new $model();
		}
	}
	
	public function loadModel($model){
		if(!isset($this->models[$model])){
			App::import('app.Model.'.$model);
			$this->models[$model] = new $model();
		}
	}
}


?>